﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace curbside.Xml
{
    public class XmlValidator
    {
        public static bool ValidateXmlFile(string file, string xsdpath, string namespaceUrl)
        {
            using (FileStream stream = new FileStream(file, FileMode.Open, FileAccess.ReadWrite))
            {
                return ValidateXmlStream(stream, xsdpath, namespaceUrl);
            }
        }

        public static bool ValidateXmlFile(string file, string xsdpath)
        {
            return ValidateXmlFile(file, xsdpath, string.Empty);
        }

        public static bool ValidateXmlString(string xmlString, string xsdpath, string namespaceUrl)
        {
            byte[] array = Encoding.ASCII.GetBytes(xmlString);
            using (MemoryStream stream = new MemoryStream(array))
            {
                return ValidateXmlStream(stream, xsdpath, namespaceUrl);
            }
        }

        public static bool ValidateXmlString(string xmlString, string xsdpath)
        {
            return ValidateXmlString(xmlString, xsdpath, string.Empty);
        }

        public static bool ValidateXmlStream(Stream stream, string xsdpath, string namespaceUrl)
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(namespaceUrl, xsdpath);

            bool flag = true;
            using (XmlReader reader = XmlReader.Create(stream, settings))
            {
                try
                {
                    reader.MoveToContent();
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Document && reader.NamespaceURI != namespaceUrl)
                        {
                            flag = false;
                            break;
                        }
                    }
                }
                catch
                {
                    flag = false;
                }
            }

            return flag;
        }
    }
}
